let isSelecting = false;
let startX, startY;
let selectionBox = null;

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'startSelection':
            startSelectionMode();
            break;
    }
});

// 开始选择模式
function startSelectionMode() {
    isSelecting = true;
    document.body.style.cursor = 'crosshair';

    // 创建选择框
    selectionBox = document.createElement('div');
    selectionBox.style.cssText = `
    position: fixed;
    border: 2px solid #4CAF50;
    background-color: rgba(76, 175, 80, 0.1);
    pointer-events: none;
    z-index: 999999;
    display: none;
  `;
    document.body.appendChild(selectionBox);

    // 添加事件监听器
    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
}

// 处理鼠标按下事件
function handleMouseDown(e) {
    if (!isSelecting) return;

    startX = e.clientX;
    startY = e.clientY;

    selectionBox.style.display = 'block';
    selectionBox.style.left = startX + 'px';
    selectionBox.style.top = startY + 'px';
    selectionBox.style.width = '0';
    selectionBox.style.height = '0';
}

// 处理鼠标移动事件
function handleMouseMove(e) {
    if (!isSelecting || !selectionBox.style.display) return;

    const currentX = e.clientX;
    const currentY = e.clientY;

    const width = Math.abs(currentX - startX);
    const height = Math.abs(currentY - startY);

    selectionBox.style.left = Math.min(startX, currentX) + 'px';
    selectionBox.style.top = Math.min(startY, currentY) + 'px';
    selectionBox.style.width = width + 'px';
    selectionBox.style.height = height + 'px';
}

// 处理鼠标释放事件
function handleMouseUp(e) {
    if (!isSelecting) return;

    const endX = e.clientX;
    const endY = e.clientY;

    // 计算选择区域
    const left = Math.min(startX, endX);
    const top = Math.min(startY, endY);
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);

    // 发送截图请求
    chrome.runtime.sendMessage({
        action: 'captureSelection',
        area: { left, top, width, height }
    });

    // 清理
    cleanup();
}

// 清理函数
function cleanup() {
    isSelecting = false;
    document.body.style.cursor = '';
    if (selectionBox) {
        selectionBox.remove();
        selectionBox = null;
    }
    document.removeEventListener('mousedown', handleMouseDown);
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
}